

import csv

import MySQLdb
import os
import glob


import os
import sys

path = os.path.dirname( __file__)
if path == "":
  base = os.getcwd()
  base = os.path.abspath(base+"\\..")
else:
  base = os.path.abspath(path+"\\..")

dbpath = base +"\\utils"

sys.path.append(dbpath)

import config

"""

try:
  from generator.utils import config
except:
  from utils import config

"""

class MySQL:

  class __MySQL:
    
    def __init__(self, schema):
      
      cfg = config.Config('project.cfg')
      dbhost = cfg.getOption('mysql','host')
      dbport = int(cfg.getOption('mysql','port'))
      dbusername = cfg.getOption('mysql','username')
      dbpassword = cfg.getOption('mysql','password')
      
      #dbschema = cfg.getOption('mysql','model_schema')    #
      dbschema = schema #cfg.getOption('mysql','project_schema')  #
      
      try:
        self.Con = MySQLdb.connect(host=dbhost, port=dbport, user=dbusername, passwd=dbpassword, db=dbschema, charset='utf8')
        self.cursor = self.Con.cursor (MySQLdb.cursors.DictCursor)
        self.cursor.execute ("set character_set_client = utf8")
        self.cursor.execute ("set character_set_connection = utf8")
        self.cursor.execute ("set character_set_results = utf8")
      except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit (1)
      
    def execute(self, sql):    
      # execute and featchone
      try:
        self.cursor.execute (sql)
        result_set = self.cursor.fetchone ()
        self.cursor.execute("commit")
        return result_set
      except MySQLdb.Error, e:
        #sql = sql.encode('GBK')
        err =  "sql:%s;\nMySQl--%d: %s\n" % (sql, e.args[0], e.args[1])
        print err

    def fetchone(self, sql):    
      # execute and featchone
      try:
        self.cursor.execute (sql)
        result_set = self.cursor.fetchone ()
        self.cursor.execute("commit")
        return result_set
      except MySQLdb.Error, e:
        #sql = sql.encode('GBK')
        err =  "sql:%s;\nMySQl--%d: %s\n" % (sql, e.args[0], e.args[1])
        print err
        
    def fetchall(self, sql):    
      # execute and featchone
      try:
        self.cursor.execute (sql)
        result_set = self.cursor.fetchall ()
        self.cursor.execute("commit")
        return result_set
      except MySQLdb.Error, e:
        #sql = sql.encode('GBK')
        err =  "sql:%s;\nMySQl--%d: %s\n" % (sql, e.args[0], e.args[1])
        print err      


  
  instance = None

  def __init__(self, schema='kylin'):
      if not MySQL.instance:
          MySQL.instance =MySQL.__MySQL(schema)            
      else:
          pass
  #print Log.instance

  def __getattr__(self, name):
    return getattr(self.instance, name)
